#include <stdlib.h>
#include <stdio.h>
#include <math.h>
/* find the ratio  nG to G mass functions.
 */
 
int main(int argc, char *argv[]) {
  if (argc==1) {
      printf("USAGE: ratio Glocation nGlocation filebase #ofseedsofdata\n Output is written in nGlocation\n");
      return 0;
  }
  char Gfilebase[150], nGfilebase[150], fname[200], string[500];
  // open the files in 
  sprintf(Gfilebase, "%s/mfn/", argv[1]);
  sprintf(nGfilebase, "%s/mfn/", argv[2]);
  float col1G[30], col2G[30], avg[30], nGloc[150], g1[30], ratio[30], col1NG[30], col2NG[30];;
  int i,j, n, ndata;
  FILE *fp;
  
  n = atoi(argv[4]);
  printf("n: %d\n", n);
  for (i=0; i<n; i++) {
    sprintf(fname, "%s%s.%d", Gfilebase, argv[3], i);
    fp = fopen(fname, "r");
    ndata=0;
    while (!feof(fp)) {
      if (fgets(string, 499, fp)) {
	sscanf(string, "%g %g %*g", &col1G[ndata], &col2G[ndata]);
	ndata++;
      }
    }
    close(fp);
    
    sprintf(fname, "%s%s.%d", nGfilebase, argv[3], i);
    fp = fopen(fname, "r");
    ndata=0;
    while (!feof(fp)) {
      if (fgets(string, 499, fp)){
	sscanf(string, "%g %g %*g", &col1NG[ndata], &col2NG[ndata]);
	ndata++;
      }
    }
    close(fp);
    // now take the ratio et al and write the output
    sprintf(fname, "%s%s.ratio.%d", nGfilebase, argv[3], i);
    fp = fopen(fname, "w");
    for (j=0; j<ndata; j++) {
      if (col2NG[j]>0 && col1NG[j]>0 && col2G[j]>0) {
	ratio[j]=col2NG[j]/col2G[j];
        avg[j]=(col1NG[j]+col1G[j])/2;
        fprintf(fp, "%g %g\n", avg[j], ratio[j]);
      }
    }
    close (fp);
    
  }
}
